import { Button, message, notification, Space } from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { couponApi } from '@/apis'
import type { CouponListItem } from '@/apis/couponTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus, optionsToMap } from '@/utils'

export default defineComponent({
  name: 'CouponManage',
  setup() {
    const statusOptions = [
      { label: '未生效', value: 0 },
      { label: '生效中', value: 1 },
      { label: '已过期', value: 2 }
    ]
    const statusMap = optionsToMap(statusOptions)

    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        toolbarConfig: {
          perfect: false,
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '码类型',
              field: 'couponType',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部类型'
                },
                options: [
                  { label: '签到券码', value: 1 },
                  { label: '拼团券码', value: 2 },
                  { label: '翻牌券码', value: 3 },
                  { label: '积分兑换券', value: 4 },
                  { label: '金豆兑好礼', value: 5 }
                ]
              }
            },
            {
              title: '状态',
              field: 'status',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部状态'
                },
                options: [
                  { label: '未生效', value: 0 },
                  { label: '生效中', value: 1 },
                  { label: '已过期', value: 2 }
                ]
              }
            },
            {
              title: '优惠券名称',
              field: 'name',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入优惠券名称'
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columns: [
          {
            type: 'checkbox',
            width: 50
          },
          {
            title: '优惠券名称',
            field: 'name'
          },
          {
            title: '码类型',
            field: 'couponTypeName'
          },
          {
            title: '面值',
            field: 'discountAmount',
            formatter: ({ row }: { row: CouponListItem }) => {
              if (row.discount) {
                return `${row.discount}折`
              }
              if (row.discountAmount) {
                return `${row.discountAmount}元`
              }
            }
          },
          {
            title: '有效时间',
            formatter: ({ row }) => {
              return `${row.startDate} - ${row.endDate}`
            }
          },
          {
            title: '状态',
            field: 'status',
            formatter: ({ cellValue }) => {
              return statusMap[cellValue]
            }
          },
          {
            title: '库存',
            field: 'stock'
          },
          {
            title: '券归属',
            field: 'belong'
          },
          {
            title: '操作',
            slots: {
              default: 'operation'
            },
            width: 250
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await couponApi.getList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const router = useRouter()
    const { showConfirm } = useDialog()

    function handleCreate() {
      router.push({
        name: 'CouponCreate'
      })
    }

    function handleEdit(item: CouponListItem) {
      const query = {
        id: item.id
      }

      if (Number(item.status) === 0) {
        query['isValid'] = true
      }

      router.push({
        name: 'CouponEdit',
        query
      })
    }

    function handleDelete(item: CouponListItem) {
      showConfirm({
        content: '确认删除？',
        onOk: async () => {
          await tableRef.value.refresh(async () => {
            await couponApi.deleteOne(item.id)
            notification.success({
              message: '删除成功',
              duration: 1.5
            })
          })
        }
      })
    }

    function handleJumpCode(item: CouponListItem) {
      router.push({
        name: 'CodeLibrary',
        query: {
          id: item.id
        }
      })
    }

    function handleBatchDelete() {
      const selected = tableRef.value.table.getCheckboxRecords().map(v => v.id)

      if (selected.length === 0) {
        return message.warn('请选择至少1条记录')
      }

      showConfirm({
        content: '确认批量删除？',
        onOk: async () => {
          await tableRef.value.refresh(async () => {
            await couponApi.deleteList(selected)
            notification.success({
              message: '批量删除成功',
              duration: 1.5
            })
          })
        }
      })
    }

    onMounted(() => {
      bus.on('refreshCouponManage', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    return {
      tableRef,
      tableConfig,
      handleCreate,
      handleDelete,
      handleEdit,
      handleJumpCode,
      handleBatchDelete
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                  disabled={row.status === 2}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDelete(row)}
                >
                  删除
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleJumpCode(row)}
                >
                  码库
                </Button>
              </Space>
            ),
            toolbarButtons: () => {
              return (
                <Space>
                  <Button onClick={this.handleCreate}>新增优惠券</Button>
                  <Button onClick={this.handleBatchDelete}>批量删除</Button>
                </Space>
              )
            }
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
